HackerRank Absolute Permutation
提出
code: python
import math
import os
import random
import re
import sys
#
# Complete the 'absolutePermutation' function below.
#
# The function is expected to return an INTEGER_ARRAY.
# The function accepts following parameters:
# 1. INTEGER n
# 2. INTEGER k
#
def absolutePermutation(n, k):
# Write your code here
ans = []
for i in range(1, n+1):
res = -1
if (i + k <= n):
res = i + k
if (i - k > 0):
res = i - k
if (res == -1):
ans.append(res)
return ans
if __name__ == '__main__':
t = int(input().strip())
for t_itr in range(t):
first_multiple_input = input().rstrip().split()
n = int(first_multiple_input0) k = int(first_multiple_input1) result = absolutePermutation(n, k)
fptr.write(' '.join(map(str, result)))
fptr.write('\n')
fptr.close()
# Just change order not to duplicate(permutation)
# 1 2 3 4 5 6 7 8 9 10
# 2 1 2 3 4 5 6 7 8 9
# 1 2 3 4 5 6 7
# -1
# 1 2 3 4 5 6 7 8 9
# 4 5 6 1 2 3 4 5 6 7 -> -1 (9 0)
# 3 4 1 2 3 4 5 6 -> 3 4 1 2 7 8 5 6 (8 2)
# 1 2 3 4 5 6 7 8
# 1 2 3 4 5 6 7
# 2 1 2 3 4 5 6 7 8 9 -> 2 1 4 3 6 5 8 7 10 9 (10 1)
解答
code: python
import math
import os
import random
import re
import sys
#
# Complete the 'absolutePermutation' function below.
#
# The function is expected to return an INTEGER_ARRAY.
# The function accepts following parameters:
# 1. INTEGER n
# 2. INTEGER k
#
def absolutePermutation(n, k):
# Write your code here
# initialize the array
a = list(range(n+1))
# k = 0
if k == 0:
# n is odd
if n % 2 == 1:
# main logic
for i in range(1, n-k+1):
# check condition
# 8 2
# swap
for i in range(n-k+1, n+1):
if __name__ == '__main__':
t = int(input().strip())
for t_itr in range(t):
first_multiple_input = input().rstrip().split()
n = int(first_multiple_input0) k = int(first_multiple_input1) result = absolutePermutation(n, k)
fptr.write(' '.join(map(str, result)))
fptr.write('\n')
fptr.close()
メモ
https://www.youtube.com/watch?v=wYP26NX8JpE
提出
code: python
import math
import os
import random
import re
import sys
#
# Complete the 'absolutePermutation' function below.
#
# The function is expected to return an INTEGER_ARRAY.
# The function accepts following parameters:
# 1. INTEGER n
# 2. INTEGER k
#
def absolutePermutation(n, k):
# (-1, 3), (0, 4), (1, 5), (2, 6), (3, 7), (4, 8), (5, 9) for i in range(1, n+1):
if i-k >= 1:
if i+k <= n:
else:
else:
elif i+k <= n:
else:
else:
ans.pop(0)
return -1 if -1 in ans else ans if __name__ == '__main__':
t = int(input().strip())
for t_itr in range(t):
first_multiple_input = input().rstrip().split()
n = int(first_multiple_input0) k = int(first_multiple_input1) result = absolutePermutation(n, k)
fptr.write(' '.join(map(str, result)))
fptr.write('\n')
fptr.close()